import json
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_dysmsapi20170525 import models as dysmsapi_models
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models

class AliyunMessage:
    def __init__(self):
        self.endpoint = 'dysmsapi.aliyuncs.com'
        # AccessKey ID
        self.access_key_id = 'LTAI5tErePct5d9kQnCMArHr'
        # AccessKey Secret
        self.access_key_secret = 'Jr2ATxo09kDjS4Ue481gHXdUBK2kg4'
        # 申请的签名
        self.sign_name = '阿里云短信测试'
        # 短信模板
        self.template_code = 'SMS_154950909'

    def send_msg(self, mobile: str, code: str):
        """
        :param mobile: 接受验证码的手机号
        :param code: 验证码内容
        :return:
        """
        send_sms_request = dysmsapi_models.SendSmsRequest(
            sign_name=self.sign_name,
            template_code=self.template_code,
            phone_numbers=mobile,
            template_param=json.dumps({"code": code})
        )
        config = open_api_models.Config(
            access_key_id=self.access_key_id,
            access_key_secret=self.access_key_secret,
            endpoint=self.endpoint
        )
        client = Dysmsapi20170525Client(config)
        runtime = util_models.RuntimeOptions()
        try:
            # 发送短信
            response = client.send_sms_with_options(send_sms_request, runtime)
            if response.body.code == 'OK':
                return {'code': "OK", "message": "短信发送成功"}
            else:
                return {'code': "NO", "error": response.body.message}
        except Exception as e:
            return {'code': "NO", "error": '短信发送失败', 'details': str(e)}

if __name__ == '__main__':
    result = AliyunMessage().send_msg('13120909379', '989829')
    print(result)
